package com.elong.businesstravel.modules.home;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.Paint.FontMetrics;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ZoomControls;

import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshBase;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshListView;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshBase.Mode;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.utils.AnimationUtils;
import com.android.support.jhf.utils.CoordinateConversion;
import com.android.support.jhf.utils.ImageUtil;
import com.android.support.jhf.utils.ToolUtils;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapStatus;
import com.baidu.mapapi.map.MKMapStatusChangeListener;
import com.baidu.mapapi.map.MKMapTouchListener;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PoiOverlay;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.map.TextItem;
import com.baidu.mapapi.map.TextOverlay;
import com.baidu.mapapi.map.MyLocationOverlay.LocationMode;
import com.baidu.mapapi.map.Symbol.Color;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.baidu.platform.comapi.map.Projection;
import com.baidu.platform.comapi.map.base.m;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.activity.BaseActivity;
import com.elong.businesstravel.base.baidusdk.location.BaiduLocation;
import com.elong.businesstravel.base.baidusdk.map.BaiduMapView;
import com.elong.businesstravel.base.baidusdk.map.BaiduMapView.LocationOverlayDispatchTap;
import com.elong.businesstravel.base.baidusdk.map.TouchMapView;
import com.elong.businesstravel.base.utils.SettingsUtils;
import com.elong.businesstravel.base.view.TitleNavBarView;
import com.elong.businesstravel.entitys.Chains;
import com.elong.businesstravel.entitys.Hotel;
import com.elong.businesstravel.entitys.HotelDocs;
import com.elong.businesstravel.entitys.HotelNameSearchResult;
import com.elong.businesstravel.entitys.HotelSearchCondition;
import com.elong.businesstravel.entitys.MyGeoPoint;
import com.elong.businesstravel.entitys.Poi;
import com.elong.businesstravel.modules.home.adapter.HotelSearchResultAdapter;
import com.elong.businesstravel.modules.home.baseactivity.BaseHotelResultActivity;
import com.elong.businesstravel.protocol.hotel.GetHotelListRequest;
import com.elong.businesstravel.protocol.hotel.GetHotelListResponse;

/**
 * 酒店搜索结果地图页
 * 
 * @author lenovo
 * 
 */
public class HotelSearchResultMapActivity extends BaseHotelResultActivity {

	// 地图相关，使用继承MapView的MyLocationMapView目的是重写touch事件实现泡泡处理
	// 如果不处理touch事件，则无需继承，直接使用MapView即可
	private MyOverlay mOverlay;
	private PopupOverlay mPopupOverlay;
	private OverlayItem mDestOverlayItem = null;
	
	// UI相关
	private Bitmap mPhoto;

	/** true表示抵扣列表跳转到map界面 */
	private boolean mPrepaidFlag = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_hotel_search_map_result);

		init();
	}

	@Override
	protected void init() {
		mCurrentHotelSearchCondition = (HotelSearchCondition) getIntent()
				.getSerializableExtra("HotelSearchCondition");
		if (-1 == SettingsUtils.getHotelFull(mContext)) {
			mCurrentHotelSearchCondition.isfull = 1;
		} else {
			mCurrentHotelSearchCondition.isfull = SettingsUtils
					.getHotelFull(mContext);
		}
		mHotel = (Hotel) getIntent().getSerializableExtra("Hotel");
		mSortByDistance = getIntent().getBooleanExtra("SortByDistance", false);
		mPrepaidFlag = getIntent().getBooleanExtra("prepaid", false);
		mDestGeoPoint = (MyGeoPoint) getIntent().getSerializableExtra("DestGeoPoint");
		
		mLongClickTextView = (TextView)findViewById(R.id.longClickTextView);
		
		super.init();

		mMapView = (TouchMapView) findViewById(R.id.mapView);
		initBaiduMap(mMapView);
		mMapView.setBuiltInZoomControls(false);

		// 点击地图上的点弹出的框
		mPopupOverlay = new PopupOverlay(mMapView, null);

		/**
		 * 创建自定义overlay 用来存放显示在地图上的点
		 */
		mOverlay = new MyOverlay(getResources()
				.getDrawable(R.drawable.ic_marka), mMapView);

		mMapView.refresh();

		/** 将overlay 添加至MapView中 ,只能添加一次 */
		mMapView.getOverlays().add(mOverlay);

		setListener();

		mHandler.sendMessage(mHandler.obtainMessage(0, mSortByDistance));

		mPhoto = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.ic_marka);

		mMapView.regMapViewListener(
				mApplication.mInitBaiduMap.getBMapManager(),
				new MKMapViewListener() {

					@Override
					public void onMapMoveFinish() {
						// HandlerToastUI.getHandlerToastUI(mContext,
						// "onMapMoveFinish");
					}

					@Override
					public void onMapLoadFinish() {
						// HandlerToastUI.getHandlerToastUI(mContext,
						// "onMapLoadFinish");
						HandlerPostUI.getHandlerPostUI(new Runnable() {
							@Override
							public void run() {

							}
						});

					}

					@Override
					public void onMapAnimationFinish() {
						// HandlerToastUI.getHandlerToastUI(mContext,
						// "onMapAnimationFinish");

						new Thread(new Runnable() {

							@Override
							public void run() {
								try {
									TimeUnit.MILLISECONDS.sleep(250);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
								HandlerPostUI.getHandlerPostUI(new Runnable() {

									@Override
									public void run() {
										if (mShowPopupFlag) {
											showPopupOverlay(mShowPopupOverlay);
										}
									}
								});
							}
						}).start();
					}

					@Override
					public void onGetCurrentMap(Bitmap arg0) {
						// HandlerToastUI.getHandlerToastUI(mContext,
						// "onGetCurrentMap");
					}

					@Override
					public void onClickMapPoi(MapPoi arg0) {
						// HandlerToastUI.getHandlerToastUI(mContext,
						// "onClickMapPoi");
					}
				});

		mMapView.regMapTouchListner(new MKMapTouchListener() {

			@Override
			public void onMapLongClick(GeoPoint arg0) {

				mDestGeoPoint = new MyGeoPoint(arg0);
				
				double[] lngLat = CoordinateConversion.bd2gg(
						(double) arg0.getLatitudeE6() / (double) 1000000,
						(double) arg0.getLongitudeE6() / (double) 1000000);

				getHotlList(false, lngLat[1], lngLat[0]);

				mMapView.refresh();
			}

			@Override
			public void onMapDoubleClick(GeoPoint arg0) {
				// HandlerToastUI.getHandlerToastUI(mContext,
				// "onMapDoubleClick");
				if (mPopupOverlay != null) {
					mPopupOverlay.hidePop();
				}
			}

			@Override
			public void onMapClick(GeoPoint arg0) {

			}
		});

		ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomControls);
		zoomControls.setOnZoomInClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (mPopupOverlay != null) {
					mPopupOverlay.hidePop();
				}
				mMapController.zoomIn();
			}
		});
		zoomControls.setOnZoomOutClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mPopupOverlay != null) {
					mPopupOverlay.hidePop();
				}
				mMapController.zoomOut();
			}
		});

	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		mSortByDistance = getIntent().getBooleanExtra("SortByDistance", false);
		mHandler.sendMessage(mHandler.obtainMessage(0, mSortByDistance));
	}

	@Override
	protected void setListener() {
		mBaiduMapView
				.setLocationOverlayDispatchTap(new LocationOverlayDispatchTap() {

					@Override
					public boolean dispatchTap() {
						// 处理点击事件,弹出泡泡
						return true;
					}
				});

		Button locButton = (Button) findViewById(R.id.locButton);
		locButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				baiduLocation();
			}
		});

		Button moreButton = (Button) findViewById(R.id.moreButton);
		moreButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				getHotelList(true);

			}
		});

		super.setListener();
	}

	@Override
	protected void updateHotelDate(boolean sortByDistance) {
		// 更新地图数据
		mHandler.sendMessage(mHandler.obtainMessage(0, sortByDistance));
	}

	private void addOverlay(MyGeoPoint p1, String hotelName) {
//		if (null != mDestOverlayItem) {
//			mOverlay.removeItem(mDestOverlayItem);
//		}
		GeoPoint geoPoint = new GeoPoint(p1.getLatitudeE6(), p1.getLongitudeE6());
		mDestOverlayItem = new OverlayItem(geoPoint, "", "");
		mDestOverlayItem.setTitle(hotelName);
		mDestOverlayItem.setMarker(getResources().getDrawable(R.drawable.ic_gcoding));

		/** 将item 添加到overlay中 注意： 同一个itme只能add一次 */
		mOverlay.addItem(mDestOverlayItem);
	
		mMapController.animateTo(geoPoint);
	}

	private void addOverlay(HotelNameSearchResult hotelNameSearchResult) {
		double baiduLat = 0;
		double baiduLng = 0;
		if (null != mApplication.mBdLocation) {
			baiduLat = mApplication.mBdLocation.getLatitude();
			baiduLng = mApplication.mBdLocation.getLongitude();
		}
		try {
			double googleLat = Double
					.parseDouble(hotelNameSearchResult.googlelat);
			double googleLng = Double
					.parseDouble(hotelNameSearchResult.googlelng);
			double[] lngLat = CoordinateConversion.gg2bd(googleLat, googleLng);
			baiduLat = lngLat[1];
			baiduLng = lngLat[0];
		} catch (Exception e) {
		}
		/**
		 * 准备overlay 数据
		 */
		GeoPoint p1 = new GeoPoint((int) (baiduLat * 1E6),
				(int) (baiduLng * 1E6));
		OverlayItem item1 = new OverlayItem(p1, "", "");
		// String price = "￥" + hotelNameSearchResult.minPrice;
		item1.setTitle(hotelNameSearchResult.hotelName);
		// item1.setSnippet(price);
		// item1.setMarker(watermark(R.drawable.ic_marka, ""));

		/** 将item 添加到overlay中 注意： 同一个itme只能add一次 */
		mOverlay.addItem(item1);

		mMapController.animateTo(p1);
	}

	private void addOverlay(HotelDocs hotelDocs, final int index) {

		double baiduLat = 0;
		double baiduLng = 0;
		if (null != mApplication.mBdLocation) {
			baiduLat = mApplication.mBdLocation.getLatitude();
			baiduLng = mApplication.mBdLocation.getLongitude();
		}
		try {
			double googleLat = Double
					.parseDouble(hotelDocs.latlng_0_coordinate);
			double googleLng = Double
					.parseDouble(hotelDocs.latlng_1_coordinate);
			double[] lngLat = CoordinateConversion.gg2bd(googleLat, googleLng);
			baiduLat = lngLat[1];
			baiduLng = lngLat[0];
		} catch (Exception e) {
		}
		/**
		 * 准备overlay 数据
		 */
		GeoPoint p1 = new GeoPoint((int) (baiduLat * 1E6),
				(int) (baiduLng * 1E6));
		OverlayItem item1 = new OverlayItem(p1, "", "");
		String price = "￥" + hotelDocs.minPrice;
		item1.setTitle(hotelDocs.hotelName);
		item1.setSnippet(hotelDocs.hotelAddress);
		item1.setMarker(ImageUtil.watermark(mPhoto, price, 23.0f,
				android.graphics.Color.WHITE));

		/** 将item 添加到overlay中 注意： 同一个itme只能add一次 */
		mOverlay.addItem(item1);

		if (0 == index && null == mDestOverlayItem) {
			mMapController.animateTo(p1);

			mShowPopupOverlay.hotelName = hotelDocs.hotelName;
			mShowPopupOverlay.hotelAddress = hotelDocs.hotelAddress;
			mShowPopupOverlay.p1 = p1;
			mShowPopupOverlay.index = 0;
			mShowPopupFlag = true;
			showPopupOverlay(mShowPopupOverlay);
		}
	}

	@Override
	protected void titleRightOnClick(String textString) {
		Intent intent = new Intent();
		if (LIST.equals(textString)) {
			if (mPrepaidFlag) {
				// 跳转到抵扣酒店列表
				intent.setClass(mContext,
						PrepaidHotelSearchResultActivity.class);
			} else {
				// 跳转到所有酒店列表
				intent.setClass(mContext, HotelSearchResultActivity.class);
			}
			intent.putExtra("activityTag", MAP);
			intent.putExtra("HotelSearchCondition",
					mCurrentHotelSearchCondition);
			intent.putExtra("sort", mHotelSort);
			intent.putExtra("Hotel", mHotel);
			intent.putExtra("prepaid", mPrepaidFlag);
			intent.putExtra("SortByDistance", mSortByDistance);
			intent.putExtra("DestGeoPoint", mDestGeoPoint);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

		}
		startActivityForResult(intent, 4);
	}

	@Override
	protected void titleLeftOnClick(String textString) {
		Intent intent = new Intent();
		if (LIST.equals(textString)) {
			if (mPrepaidFlag) {
				// 跳转到抵扣酒店列表
				intent.setClass(mContext,
						PrepaidHotelSearchResultActivity.class);
			} else {
				// 跳转到所有酒店列表
				intent.setClass(mContext, HotelSearchResultActivity.class);
			}
			intent.putExtra("activityTag", MAP);
			intent.putExtra("HotelSearchCondition",
					mCurrentHotelSearchCondition);
			intent.putExtra("sort", mHotelSort);
			intent.putExtra("Hotel", mHotel);
			intent.putExtra("SortByDistance", mSortByDistance);
			intent.putExtra("DestGeoPoint", mDestGeoPoint);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		}
		startActivityForResult(intent, 4);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		default:
			break;
		}
	}

	private Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case 0: {
				if (null != hotelNameSearchResult) {
					mHotelNameTextView.setVisibility(View.VISIBLE);
					mHotelNameLayout.setVisibility(View.VISIBLE);

					String nameString = hotelNameSearchResult.hotelName;
					if (TextUtils.isEmpty(nameString)) {
						nameString = hotelNameSearchResult.districtsname;
					}

					if (TextUtils.isEmpty(nameString)) {
						nameString = hotelNameSearchResult.bussinename;
					}

					if (TextUtils.isEmpty(nameString)) {
						nameString = hotelNameSearchResult.name;
					}

					if (TextUtils.isEmpty(nameString)) {
						nameString = hotelNameSearchResult.shortname;
					}
					mHotelNameTextView.setText(nameString);
					// mSearchTextView.setVisibility(View.INVISIBLE);
					mSearchTopLayout.setVisibility(View.INVISIBLE);

				} else if (!TextUtils
						.isEmpty(mCurrentHotelSearchCondition.keyword)) {
					mHotelNameTextView.setVisibility(View.VISIBLE);
					mHotelNameLayout.setVisibility(View.VISIBLE);
					mHotelNameTextView
							.setText(mCurrentHotelSearchCondition.keyword);
					// mSearchTextView.setVisibility(View.INVISIBLE);
					mSearchTopLayout.setVisibility(View.INVISIBLE);
				} else {
					mHotelNameTextView.setVisibility(View.GONE);
					mHotelNameLayout.setVisibility(View.GONE);
					if ("".equals(mCurrentHotelSearchCondition.keyword)) {
						mHotelNameTextView
								.setText(mCurrentHotelSearchCondition.keyword);
					}
					// mSearchTextView.setVisibility(View.INVISIBLE);
					mSearchTopLayout.setVisibility(View.VISIBLE);
				}
				if (mPopupOverlay != null) {
					mPopupOverlay.hidePop();
				}

				mOverlay.removeAll();
				mDestOverlayItem = null;

				if (null != hotelNameSearchResult
						&& !TextUtils.isEmpty(hotelNameSearchResult.googlelat)
						&& !TextUtils.isEmpty(hotelNameSearchResult.googlelng) 
						&& !TextUtils.isEmpty(hotelNameSearchResult.hotelName)){
					addOverlay(hotelNameSearchResult);
				}else {
					
				}

				if("目的地".equals(mCurrentHotelSearchCondition.mSearchConditionPoi.name)){
					
					addOverlay(mDestGeoPoint, "目的地");
				}
				
				// mHotelSearchResultAdapter.notifyDataSetChanged();
				for (int i = 0; i < mHotel.mHotelDocs.size(); i++) {
					addOverlay(mHotel.mHotelDocs.get(i), i);
				}
				mMapView.refresh();

				boolean sortByDistance = (Boolean) msg.obj;
				if (sortByDistance) {
					// 修改排序，按照距离排序
					if (-1 == mCurrentHotelSearchCondition.sorts) {
						mCurrentHotelSearchCondition.sorts = 4;
					}
					mHotelSort = mApplication.mHotelLocSorts;
				} else {
					// 默认排序
					// mCurrentHotelSearchCondition.sorts = 0;
					mHotelSort = mApplication.mHotelSorts;
				}

				break;
			}
			case 1: {
				break;
			}
			default:
				break;
			}
			return false;
		}
	});

	public class MyOverlay extends ItemizedOverlay<OverlayItem> {

		public MyOverlay(Drawable defaultMarker, MapView mapView) {
			super(defaultMarker, mapView);
		}

		@Override
		public boolean onTap(final int index) {
			OverlayItem item = getItem(index);
			if (null == item) {
				return true;
			}
			String hotelName = item.getTitle();
			GeoPoint geoPoint = item.getPoint();
			String hotelAddress = item.getSnippet();

			mShowPopupOverlay.hotelName = hotelName;
			mShowPopupOverlay.hotelAddress = hotelAddress;
			mShowPopupOverlay.p1 = geoPoint;
			mShowPopupOverlay.index = index;
			mShowPopupFlag = true;
			showPopupOverlay(mShowPopupOverlay);
			return true;
		}

		@Override
		public boolean onTap(GeoPoint pt, MapView mMapView) {
			if (mPopupOverlay != null) {
				mShowPopupFlag = false;
				mPopupOverlay.hidePop();
			}
			return false;
		}

	}

	private void showPopupOverlay(ShowPopupOverlay showPopupOverlay) {
		final String hotelName = showPopupOverlay.hotelName;
		String hotelAddress = showPopupOverlay.hotelAddress;
		GeoPoint geoPoint = showPopupOverlay.p1;
		final int index = showPopupOverlay.index;

		View view = LayoutInflater.from(mContext).inflate(
				R.layout.view_popupoverlay, null);

		// View viewDest = LayoutInflater.from(mContext).inflate(
		// R.layout.view_popupoverlay_dest, null);
		//
		// ViewGroup destLayout = (ViewGroup) viewDest
		// .findViewById(R.id.destLayout);
		// destLayout.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		//
		// }
		// });
		ViewGroup popupLayout = (ViewGroup) view.findViewById(R.id.popupLayout);

		popupLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!"目的地".equals(hotelName)) {
					Intent intent = new Intent(mContext,
							HotelDetailActivity.class);
					intent.putExtra("hotelDocs", mHotel.mHotelDocs.get(index));
					intent.putExtra("product",
							mCurrentHotelSearchCondition.product);
					startActivity(intent);
				}
			}
		});
		TextView hotelNameTextView = (TextView) view
				.findViewById(R.id.hotelNameTextView);
		hotelNameTextView.setText(hotelName);

		TextView hotelAddressTextView = (TextView) view
				.findViewById(R.id.hotelAddressTextView);
		hotelAddressTextView.setText(hotelAddress);

		Button hotelInfoButton = (Button) view
				.findViewById(R.id.hotelInfoButton);
		hotelInfoButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent(mContext,
				// HotelDetailActivity.class);
				// intent.putExtra("hotelDocs", mHotel.mHotelDocs.get(index));
				// intent.putExtra("product",
				// mCurrentHotelSearchCondition.product);
				// startActivity(intent);
			}
		});
		// if ("目的地".equals(hotelName)) {
		// mPopupOverlay.showPopup(viewDest, geoPoint, 30);
		// }else {
		mPopupOverlay.showPopup(view, geoPoint, 30);
		// }
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			titleLeftOnClick(mActivityTag);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
